# coding=UTF-8
# author=suemi
# created at 16/5/13

import json

import datetime

from utils.Constants import DATETIME_FORMAT


class BaseEntity(object):
    """
    反射方法来与数据库以及json、Item相互转化
    """

    def fields(self):
        """
        :return: 本类定义的所有变量名
        """

        candidates = list(self.__dict__.items()) + list(self.__class__.__dict__.items())
        candidates = map(lambda x: x[0],
                         filter(lambda x: not callable(x[1]) and not x[0].startswith('__'),
                                candidates))
        return list(set(candidates))

    def fromDict(self,srcMap):
        tuples = map(lambda x: (x, srcMap.get(x)), self.fields())
        candidates = list(filter(lambda x: x[0] in srcMap.keys(), tuples))
        for key, value in candidates:
            self.__dict__[key] = value
        return self

    def fromJson(self, jsonstr):
        jsonObject = json.loads(jsonstr)
        return self.fromDict(jsonObject)


    def fromItem(self,item):
        return self.fromDict(item)

    def fromRow(self,row):
        pass

    def toJson(self):
        return json.dumps(self, default=BaseEntity.jsonDefault)

    def toDict(self):
        return self.__dict__

    def documentId(self):
        pass

    @staticmethod
    def jsonDefault(x):
        if isinstance(x,set):
            return list(x)
        elif isinstance(x,datetime.datetime):
            return x.strftime(DATETIME_FORMAT)
        else:
            return x.__dict__